package cn.acmsmu.oauth.demo.facade;

import cn.acmsmu.oauth.demo.consts.OAuthConsts;
import cn.acmsmu.oauth.demo.utils.NetUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Desc:
 * @Author: huangzhiyuan
 * @CreateDate: 2023/4/11 22:25
 * @Modify:
 */
@Component
public class OAuthFacade {

    private String TOKEN = "";

    public String getToken(String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("client_id", OAuthConsts.CLIENT_ID);
        param.put("client_secret", OAuthConsts.CLIENT_SECRET);
        param.put("code", code);
        param.put("accept", "JSON");
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
        String body = (String) NetUtil.doPost("https://github.com/login/oauth/access_token", param, String.class);
        String[] msgArr = body.split("&");
        Map<String, String> msgMap = new HashMap<>();
        for (String msg : msgArr) {
            String[] temp = msg.split("=");
            if (temp.length == 2) {
                msgMap.put(temp[0], temp[1]);
            } else {
                msgMap.put(temp[0], null);
            }
        }
        if (msgMap.get("access_token") != null) {
            TOKEN = msgMap.get("access_token");
        }
        return JSON.toJSONString(msgMap);
    }

    public String getUserInfo() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", "application/vnd.github+json");
        headers.set("Authorization", "Bearer " + TOKEN);
        headers.set("X-GitHub-Api-Version", "2022-11-28");
        String body = (String) NetUtil.doGet("https://api.github.com/user", null, headers, String.class);
        return body;
    }
}
